import http.server
import urllib.parse
from PySide6.QtCore import QThread,Signal

import IntradayRealTime
from api.thsApi.testThs import send_code_message
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
# 定义一个线程安全的HTTPServer
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

# 定义一个HTTP请求处理器
class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print('http收到请求:{}'.format(self.path))
        # 处理GET请求的逻辑
        self.send_response_only(200)  # 返回状态码200（表示成功）
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()  # 结束头部信息
        # 解析 URL 中的参数
        query = urllib.parse.urlparse(self.path).query
        params = urllib.parse.parse_qs(query)  # 将查询字符串转换为字典
        if self.path.find('/scqx') != -1:
            codes = params.get('codes')
            if codes is not None and len(codes) > 0:
                code = codes[0]
                before_comma = ''
                if code.find(',') != -1:
                    before_comma = code.split(',')[0]
                else:
                    before_comma = code
                if before_comma is not None and len(before_comma) > 0:
                    print('跳转到：{}'.format(before_comma))
                    #send_code_message(before_comma)
                    self.server.new_request.emit(before_comma)  # 发送信号
        self.wfile.write(b'Hello, world!')

# 自定义信号
class HttpAppThread(QThread):
    new_request = Signal(str)  # 定义一个信号，用于发送请求消息

    def run(self):
        # 在线程中启动HTTP服务器
        server_address = ('', IntradayRealTime.port_global)
        httpd = ThreadingHTTPServer(server_address, RequestHandler)
        httpd.new_request = self.new_request  # 将信号连接到服务器实例
        httpd.serve_forever()

def create_httpServer(port):
    server_address = ('', port)
    httpd = http.server.HTTPServer(server_address, MyHandler)
    httpd.serve_forever()


class MyHandler(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        print('http收到请求:{}'.format(self.path))
        # 处理GET请求的逻辑
        self.send_response_only(200)  # 返回状态码200（表示成功）
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()  # 结束头部信息
        # 解析 URL 中的参数
        query = urllib.parse.urlparse(self.path).query
        params = urllib.parse.parse_qs(query)  # 将查询字符串转换为字典
        if self.path.find('/scqx') != -1:
            codes = params.get('codes')
            if codes is not None and len(codes)>0:
                code = codes[0]
                before_comma = ''
                if code.find(',')!= -1:
                    before_comma = code.split(',')[0]
                else:
                    before_comma = code
                if before_comma is not None and len(before_comma)>0:
                    print('跳转到：{}'.format(before_comma))
                    send_code_message(before_comma)
        self.wfile.write(b'Hello, world!')
